package org.oimwrapper.connectors.common;

import org.oimwrapper.connectors.*;

/**
 * Revokes all instances a resource object.<p>
 *
 * This task expects the following parameters, in addition to the standard
 * parameters in the {@link OIMTaskBase} class.
 * <ul>
 * <li><code>ObjectName</code> The name of the resource object to revoke all instances of.</li>
 * <li><code>ExecuteRevokeTasks</code> Set this to <code>true</code> if the revoke process tasks 
 *                                     in OIM should be executed, and <code>false</code> if the 
 *                                     resource object should just be marked as revoked in OIM 
 *                                     without executing the process tasks.</li>
 * </ul>
 */
public class OIMRevokeAll extends OIMTaskBase {

	/**
	 * True if a stop has been requested for this task.
	 */
	private boolean stop;

	/**
	 * Default constructor.
	 */
	public OIMRevokeAll() {
		super("OIMWRAPPER.TASK");
		stop = false;
	}

	/**
	 * This method is called by the scheduler to execute the task instance.
	 */
	public void execute() {
		try {
			String objectName = getCriticalAttribute("ObjectName");
			logger.warn("Starting revocation for all " + objectName + " objects.");
			if (getBooleanAttribute("ExecuteRevokeTasks", false)) {
				OIMObjectInstanceTriple[] items = getDetailedInstances(objectName);
				for (int i = 0; !stop && i < items.length; i++) {
					long userKey = items[i].getUserKey();
					long objectInstanceKey = items[i].getObjectInstanceKey();
					deleteOimResource(userKey, objectInstanceKey);
					logger.warn("Revoked " + objectName + " " + Integer.toString(i + 1) + " of " + Integer.toString(items.length));
				}
			} else {
				executeOimQuery("update oiu set ost_key = (select ost_key from ost where obj_key in (select obj_key from obj where obj_name='" + objectName + "') and ost_status='Revoked') where obi_key in (select obi_key from obi where obj_key in (select obj_key from obj where obj_name='" + objectName + "'))");
				executeOimQuery("update orc set orc_status='X' where orc_key in (select orc_key from oiu where obi_key in (select obi_key from obi where obj_key in (select obj_key from obj where obj_name = '" + objectName + "')))");
			}
			logger.warn("Finished revocation for all " + objectName + " objects.");
		} catch (Exception e) {
			OIMExceptionHandler.handleException(logger, e, getClass());
		}
	}

	/**
	 * This method is called by the scheduler to stop a running task instance.
	 * 
	 * @return <code>true</code>
	 */
	public boolean stop() {
		logger.warn(" ---- Stopping current task ---- ");
		stop = true;
		return stop;
	}
}